package service

import (
	"gomicro/memberMicro/model"
	"gomicro/memberMicro/fjmServer/dao"
	"gomicro/memberMicro/fjmServer/brokerValue"
	"github.com/micro/go-micro/v2/broker"
	"fmt"
	"log"
	"encoding/json"
)

type MemberSriImp struct{
	Dip *dao.MemberDaoImp
}

func (msi *MemberSriImp)InesrtSri(mb []*model.Member)map[string]string{
	var d = dao.MemberDaoImp{}
	msi.Dip = &d
	return msi.Dip.InesrtDao(mb)
}

func (msi *MemberSriImp)QuerySri() []*model.Member{
	var d = dao.MemberDaoImp{}
	msi.Dip = &d
	fmt.Println(msi.Call())
	return msi.Dip.QueryDao()
}

func (msi *MemberSriImp)Call()map[string]string{
	
	student := &model.Student{Id : "30", Name: "davie老师", Birth: "2001-09-23", Sex: "男",}
	msgBody, err := json.Marshal(student)
	if err != nil {
		log.Fatal(err.Error())
	}

	msg := &broker.Message{
		Header: map[string]string{
			"Method" : "insert",
		},
		Body: msgBody,
	}

	err = brokerValue.Pub.Publish("go.micro.student.message", msg)
	if err != nil {
		log.Fatal(" 消息发布失败：%s\n", err.Error())
	} else {
		log.Print("消息发布成功")
	}	
	
	var req map[string]string
	_, sErr := brokerValue.Pub.Subscribe("go.micro.member.message", func(event broker.Event) error {

		fmt.Println("消息体:", string(event.Message().Body))

		if jErr := json.Unmarshal(event.Message().Body, &req); jErr != nil {
			return jErr
		}
		fmt.Println(" 接收到信息：", req)
		
		return nil
	})

	if sErr != nil {
		log.Printf("sub error: %v\n", sErr)
	}

	defer brokerValue.Pub.Disconnect()

	return req
}
